package com.xnx.bincker.mydoc.utils;

import com.sun.javadoc.*;
import com.sun.tools.javadoc.Main;
import lombok.NonNull;

import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;

public class JavaDocUtils extends Doclet {
    private static ThreadLocal<RootDoc> rootDocThreadLocal = new ThreadLocal<>();
    private RootDoc rootDoc;

    public JavaDocUtils(String[] classPath, String[] sourcePath, String[] files) {
        init(classPath, sourcePath, files);
    }

    public JavaDocUtils(String[] sourcePath, String[] files) {
        String[] classPath = Optional.ofNullable(System.getProperty("java.class.path"))
                .orElse("")
                .split(File.pathSeparator);
        init(classPath, sourcePath, files);
    }

    public JavaDocUtils(String... files) {
        this(new String[]{System.getProperty("user.dir") + "/src/main/java".replaceAll("/", File.separator)}, files);
    }

    /**
     * 获取rootdoc
     * @param classPath 依赖路径
     * @param sourcePath 源码路径
     * @param files 源码相对路径，或包名
     */
    private void init(String[] classPath, String[] sourcePath,@NonNull String[] files){
        List<String> args = new LinkedList<>();
        args.add("-private");
        args.add("-doclet");
        args.add(JavaDocUtils.class.getName());
        if(classPath != null && classPath.length > 0){
            args.add("-classpath");
            args.add(String.join(File.pathSeparator, classPath));
        }
        if(sourcePath != null && sourcePath.length > 0){
            args.add("-sourcepath");
            args.add(String.join(File.pathSeparator, sourcePath));
        }
        args.add(String.join(" ", files));
        Main.execute(args.toArray(new String[]{}));
        RootDoc rootDoc = rootDocThreadLocal.get();
        assert rootDoc != null;
        this.rootDoc = rootDoc;
    }

    public synchronized static boolean start(RootDoc rootDoc){
        rootDocThreadLocal.set(rootDoc);
        return true;
    }
}
